<?php

class BaseAction extends Action
{
    public function _initialize()
    {

    }

    /**
     * 操作错误提示信息
     *
     * @param String $message
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function errorMessage($message)
    {
        if ($message) {
            $this->assign('errorMessage', $message);
        }
    }

    /**
     * 操作成功提示信息
     *
     * @param String $message
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function successMessage($message)
    {
        if ($message) {
            $this->assign('successMessage', $message);
        }
    }

    /**
     * 操作提示信息
     *
     * @param String $message
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function noticeMessage($message)
    {
        if ($message) {
            $this->assign('noticeMessage', $message);
        }
    }

    /**
     * 获取登陆用户标识
     *
     * @author ice<iceinto@mallog.com.cn>
     */
    function getLoginUserInfo()
    {
        return intval($_SESSION [C('USER_AUTH_KEY')]);
    }

    /**
     * 设置登陆用户标识
     *
     * @param int $uid
     *            用户标识
     * @author ice<iceinto@mallog.com.cn>
     */
    function setLoginUserInfo($uid)
    {
        $_SESSION [C('USER_AUTH_KEY')] = $uid;
    }

    /**
     * 自动表单令牌验证
     *
     * @param array $data
     * @return null or boolean
     * @author ice<iceinto@mallog.com.cn>
     */
    function autoCheckToken($data = null)
    {
        if ($data == null) {
            $data = $_POST;
        }
        $rs = M()->autoCheckToken($data);
        if ($rs) {
            return true;
        } else {
            $this->error(L('_TOKEN_ERROR_'));
        }
    }

    /**
     * 获取分页信息
     *
     * @param Int $count
     *            总条数
     * @param int $pageSize
     *            每页显示条数
     * @return class Page
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getPage($count, $pageSize = 15)
    {
        return new Page ($count, $pageSize);
    }

    /**
     * 执行文件上传功能
     *
     * @param String $type
     *            上传类型
     * @param String $IsDate
     *            是否根据时间生成目录
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function uploadFiles($type = '', $isDate = true)
    {
        /**
         * 'name' => string 'dddddddddddddddddddddddddddddddddd.jpg' (length=38)
         * 'type' => string 'image/jpeg' (length=10)
         * 'size' => int 625330
         * 'key' => int 0
         * 'extension' => string 'jpg' (length=3)
         * 'savepath' => string 'E:/wamp/www/uploads/brand/' (length=26)
         * 'savename' => string '4dd0ddd87c495.jpg' (length=17)
         * 'hash' => string '6b238238328f6e407cf58ca0a0efe22d' (length=32)
         */
        $info = null;
        import("@.ORG.Net.UploadFile");
        $upload = new UploadFile (); // 实例化上传类
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->allowExts = array(
            'jpg',
            'png'
        ); // 设置附件上传类型
        $upload->saveRule = 'uniqid';
        if ($type != '' && $isDate) {
            // 执行品牌图片上传
            $time = date('Y/m/d');
            $savePath = UPLOAD_PATH . $type . '/' . $time . '/';
            // 循环生成上面目录
            mk_dir($savePath);
            $upload->savePath = $savePath;
        } else if ($type != '') {
            $upload->savePath = UPLOAD_PATH . $type . '/';
        } else {
            $upload->savePath = UPLOAD_PATH; // 设置附件上传目录
        }
        if (!$upload->upload()) {
            // 上传错误提示错误信息
            $this->error($upload->getErrorMsg());
        } else { // 上传成功 获取上传文件信息
            $info = $upload->getUploadFileInfo();
            // 执行数据库信息保存
            $FileManagedModel = M('FileManaged' . ucwords($type));
            $data ['uid'] = $this->getLoginUserInfo();
            $data ['name'] = $info [0] ['name'];
            $data ['uri'] = $info [0] ['savename'];
            $data ['mime'] = $info [0] ['type'];
            $data ['size'] = $info [0] ['size'];
            $data ['create_time'] = time();
            $data ['type'] = $type;
            $info ['id'] = $FileManagedModel->add($data);
        }
        return $info ['id'];
    }

    /**
     * 根据图片标示上传图片
     *
     * @param Int $fId
     *            文件标识
     * @param String $type
     *            上传类型
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function delUpLoadFile($fId, $type = '', $isDate = true)
    {
        $FileManagedModel = M('FileManaged' . ucwords($type));
        $map ['id'] = $fId;
        $file = $FileManagedModel->where($map)->find();
        if ($file) {
            $fildPath = '';
            if ($type != '') {
                // 执行品牌图片上传
                if ($isDate) {
                    // 解析时间
                    $time = strftime('%Y/%m/%d', $file ['create_time']);
                    $fildPath = UPLOAD_URL . $type . '/' . $time . '/' . $file ['uri'];
                } else {
                    $fildPath = UPLOAD_PATH . $type . '/' . $file ['uri'];
                }
            } else {
                $fildPath = UPLOAD_PATH . $file ['uri']; // 设置附件上传目录
            }
            // 实行文件删除
            if (unlink($fildPath)) {
                $FileManagedModel->where($map)->delete(); // 数据表信息删除
            }
        }
    }

    /**
     * 根据类型获取图片完整显示
     *
     * @param String $type
     *            上传类型
     * @param String $isDate
     *            是否有时间设置
     * @return String 图片地址
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getManagedUrl($id, $type = '', $isDate = true)
    {
        $defaultImages = UPLOAD_URL . 'default.jpg';
        $FileManagedModel = M('FileManaged' . ucwords($type));
        $map = array();
        if ($id) {
            $map ['id'] = $id;
            $file = $FileManagedModel->where($map)->find();
            // dump($FileManagedModel->getLastSql());
            // dump($fImages);
            if ($file) {
                if ($type && !$isDate) {
                    return UPLOAD_URL . $type . '/' . $file ['uri'];
                } else if ($type && $isDate) {
                    // 解析时间
                    $time = strftime('%Y/%m/%d', $file ['create_time']);
                    // 返回时间地址
                    return UPLOAD_URL . $type . '/' . $time . '/' . $file ['uri'];
                } else {
                    return UPLOAD_URL . $file ['uri'];
                }
            }
            return $defaultImages;
        }
        return $defaultImages;
    }

    /**
     * Error
     *
     * @param string $name
     *            name
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function errorLang($name)
    {
        $this->error(L($name));
    }

    /**
     * Error
     *
     * @param string $name
     *            name
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function successLang($name)
    {
        $this->success(L($name));
    }

    /**
     * Error
     *
     * @param string $name
     *            name
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function loginUrl($uid)
    {
        $map ['user_id'] = $uid;
        $role = M('RoleUser')->where($map)->find();
        $roles = array(1, 2, 3, 5);
        $url = __APP__;
        if ($role ['role_id'] == 4) {
            //判断是否分配商场权限如果没有分配登陆失败并且提示权限问题
        } else if (in_array($role ['role_id'], $roles)) {
            $url = __APP__ . '/Task';
        } else {
            $this->error(L('_NOT_ACCESS'));
        }

        $this->setLoginUserInfo($uid);
        redirect($url);
    }

    /**
     * 使用正则验证数据
     * @access public
     * @param string $value  要验证的数据
     * @param string $rule 验证规则
     * @return boolean
     */
    public function regex($value, $rule)
    {
        $validate = array(
            'require' => '/.+/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
            'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
            'currency' => '/^\d+(\.\d+)?$/',
            'number' => '/^\d+$/',
            'zip' => '/^[1-9]\d{5}$/',
            'integer' => '/^[-\+]?\d+$/',
            'double' => '/^[-\+]?\d+(\.\d+)?$/',
            'english' => '/^[A-Za-z]+$/',
        );
        // 检查是否有内置的正则表达式
        if (isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule, $value) === 1;
    }

    /**
     * 将给定用户设为在线
     * @param int $uid
     * @param int $t
     * @author ice <iceinto@mallog.com.cn>
     */
    public function setOnline($uid, $t = 5)
    {
        $cookie_name = 'task_login_time_' . $uid;
        $cookie_time = intval(Cookie::get($cookie_name));
        $now = time();
        $expire = $t * 60; // 有效期: 5min
        if ($cookie_time < ($now - $expire)) {
            Cookie::set($cookie_name, $now, $expire);
            $sql = 'REPLACE INTO ' . C('DB_PREFIX') .
                'user_online (`uid`,`ctime`,`ip`) VALUES ("' . $uid . '", "' . $now . '", "' . get_client_ip() . '")';
            return M('')->query($sql);
        } else {
            return null;
        }
    }

    /**
     * 获取当前在线用户数
     * @param int $t
     * @return int
     * @author ice <iceinto@mallog.com.cn>
     */
    public function getOnlineUserCount($t = 5)
    {
        $time = time() - $t * 60;
        $sql = "SELECT COUNT(*) AS count FROM " . C('DB_PREFIX') .
            "user_online WHERE `ctime` > '$time'";
        $res = M('')->query($sql);
        return $res[0]['count'];
    }

    /**
     * 用户登录IP记录
     * @param int $uid 用户标示
     * @author Ice <iceinto@mallog.com.cn>
     */
    function loginLog($uid)
    {
        $data = array();
        $LoginLogModel = M('LoginLog');
        $data['uid'] = $uid;
        $data['login_ip'] = get_client_ip();
        $data['login_time'] = time();
        $LoginLogModel->add($data);
    }

    function AjaxHead()
    {
        @header("Pragma:no-cache\r\n");
        @header("Cache-Control:no-cache\r\n");
        @header("Expires:0\r\n");
    }

    /**
     * 获取当天时间
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getThisDayTime()
    {
        import("@.ORG.Util.Date");
        $date = new Date();
        $dayTime = $date->format('%Y-%m-%d');
        return strtotime($dayTime);
    }

    /**
     * 获取年
     * @param int $month
     */
    public function getYears($year = 0)
    {
        $year = 2012;
        $years = array();
        for ($i = date('Y'); $i >= $year; $i--) {
            $years[] = array('year' => $i, 'isNow' => ($i == $year));
        }
        return $years;
    }

    /**
     * 获取月份
     * @param int $month
     */
    public function getMonths($month = 0)
    {
        if (empty($month)) {
            $month = date('n'); // n 数字表示的月份，没有前导零1 到 12
        }
        $months = array();
        for ($i = 1; $i <= 12; $i++) {
            $months[] = array('month' => $i, 'isNow' => ($i == $month));
        }
        return $months;
    }
}

?>